/*
 * Copyright 2011, 2012 Chris Banes.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sczmgk.hotline_pzh.photo;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.bitmapfun.util.AsyncTask;
import com.android.bitmapfun.util.ImageWorker;
import com.android.bitmapfun.util.LoadImage;
import com.android.bitmapfun.util.LoadImageFile;
import com.android.bitmapfun.util.LoadImageUrl;
import com.android.bitmapfun.util.MyImageFetcher;
import com.sczmgk.hotline_pzh.R;
import com.sczmgk.hotline_pzh.dialog.DialogFactory;
import com.sczmgk.hotline_pzh.photo.entity.PictureData;
import com.sczmgk.hotline_pzh.photo.entity.PictureData.UrlOrPathStata;
import com.sczmgk.hotline_pzh.popup.PupDialog;
import com.sczmgk.hotline_pzh.popup.PupDialog.PupEvent;
import com.sczmgk.hotline_pzh.utils.FileUtil;
import com.sczmgk.hotline_pzh.utils.MyLog;
import com.sczmgk.hotline_pzh.utils.MyToast;
import com.sczmgk.hotline_pzh.utils.PictureUtil;
import com.sczmgk.hotline_pzh.utils.UiUtilities;

import uk.co.senab.photoview.PhotoView;


/**
 * 通过Viewpager形式展示相册中的图片
 * @author bo
 *
 */
public class ViewPagerActivity extends Activity implements OnClickListener {

    private static final String TAG = ViewPagerActivity.class.getSimpleName();

    public class Param {

        public static final String INTENT_KEY_PICTURES = "pictures";

        public static final String INTENT_KEY_INDEX = "index";

        public static final String INTENT_KEY_FLAG = "flag";

        public static final String INTENT_KEY_MSG_USERNAME = "msg_username";

        public static final String INTENT_KEY_MSG_ID = "msg_id";
        
        public static final String INTENT_KEY_CHOOSE_COUNT = "choose_count";
        
        public static final String INTENT_KEY_MAX_CHOOSE_COUNT = "max_choose_count";
        
        public static final int FLAG_MSGCHAT = 101;
        public static final int FLAG_PUBLISH = 102;
        public static final int FLAG_FRIEND = 103;
        public static final int FLAG_CHOOSE_PHOTO = 104;

        public static final int TITLE_RIGHT_SHOW__NONE = 0;// 右边标题不显示
    }

    /** 数据 */
    private int index;
    private int flag;
    private ArrayList<PictureData> pictures = null;

    private FrameLayout mainMereg;
    private ViewPager mViewPager;
    private SamplePagerAdapter adapter;
    private ProgressBar bar;
    private LinearLayout header,bottom;
    private Button rightbt, leftbt;
    private ImageView checkBox;
    private TextView title;
    private PupDialog menuWindow;
    /**
     * 当前用户选择图片张数
     */
    private int curSelectedCount = 0;
    private int maxSelectCount = 0;
    
    private ArrayList<Integer> leftData;
    private Set<Bitmap> bitmapSets = new HashSet<Bitmap>();

    /**
     * 图片大图查看的跳转
     * 
     * @param context
     * @param pictures 图片数据
     * @param flag 从哪里跳转过来
     * @param index 显示第几张图片
     */
    public static void actionViewPager(Context context, ArrayList<PictureData> pictures, int flag, int index) {
        Intent intent = new Intent(context, ViewPagerActivity.class);
        intent.putParcelableArrayListExtra(Param.INTENT_KEY_PICTURES, pictures);
        intent.putExtra(Param.INTENT_KEY_FLAG, flag);
        intent.putExtra(Param.INTENT_KEY_INDEX, index);
        context.startActivity(intent);
    }
    
    /**
     * 聊天消息界面点击了图片
     */
    public static void actionStart(Context context, String username, String msgId) {
        Intent intent = new Intent(context, ViewPagerActivity.class);
        intent.putExtra(Param.INTENT_KEY_MSG_USERNAME, username);
        intent.putExtra(Param.INTENT_KEY_MSG_ID, msgId);
        intent.putExtra(Param.INTENT_KEY_FLAG, Param.FLAG_MSGCHAT);
        context.startActivity(intent);
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView();
        flag = getIntent().getIntExtra(Param.INTENT_KEY_FLAG, 0);
        // username和msgid是聊天界面传入的
        String username = getIntent().getStringExtra(Param.INTENT_KEY_MSG_USERNAME);
        String msgId = getIntent().getStringExtra(Param.INTENT_KEY_MSG_ID);
        if (!TextUtils.isEmpty(username)) {
        
            new LoadMessageImgTask(getApplicationContext(), username, msgId).executeParallel();//加载图片
        } else {
            pictures = getIntent().getParcelableArrayListExtra(Param.INTENT_KEY_PICTURES);
            index = getIntent().getIntExtra(Param.INTENT_KEY_INDEX, 0);
            curSelectedCount = getIntent().getIntExtra(Param.INTENT_KEY_CHOOSE_COUNT, 0);
            maxSelectCount = getIntent().getIntExtra(Param.INTENT_KEY_MAX_CHOOSE_COUNT, 0);
            setAdapter();
            initHeadStyle();
        }
    }
    /**
     * 初始化头像样式
     */
    private void initHeadStyle(){
    	if(flag == Param.FLAG_CHOOSE_PHOTO){
    		setOpertionDivVisible(true);
    		header.setBackgroundColor(getResources().getColor(R.color.common_grey_bg));
    		bottom.setBackgroundColor(getResources().getColor(R.color.common_grey_bg));
    	}
    }
    
    private static class MessageImgStatus {
        ArrayList<PictureData> ps;
        int index;
    }

    private class LoadMessageImgTask extends AsyncTask<Void, Void, MessageImgStatus> {
        private Context context;
        private String username;
        private String msgId;

        public LoadMessageImgTask(Context context, String username, String msgId) {
            this.context = context;
            this.username = username;
            this.msgId = msgId;
        }

        @Override
        protected MessageImgStatus doInBackground(Void... params) {
        	
        	
        	
//            // 查询所有有图片的消息
//            List<DroidMsg> msgs = new MessageDB(username).getMessageByMsgType(DroidMsg.CONTENT_TYPE_IMAGE);
//            MessageImgStatus s = new MessageImgStatus();
//            ArrayList<PictureData> pictures = new ArrayList<PictureData>();
//            PictureData data = null;
//            int index = 0;
//            int i = 0;
//            for (DroidMsg msg : msgs) {
//                if (msgId.equals(msg.getMsgId())) {
//                    index = i;
//                }
//                i++;
//                data = new PictureData();
//                Log.d(TAG,
//                        String.format("msg %s %s %s %s", msg.getMsgProto(), msg.getContent(), msg.getLocalPath(),
//                                msg.getIsUpLoad()));
//                // 优先使用网络地址
//                if (ChatMessageView.isSendMessage(msg)) {
//                    if (msg.getIsUpLoad() == DroidMsg.UPLOAD_DOING) {
//                        data.setmUrl(msg.getContent());
//                        data.setUrlOrPath(UrlOrPathStata.STATE_PATH);
//                    } else {
//                        // 发送消息，local字段存的是网络地址，content字段存的是本地地址
//                        if (TextUtils.isEmpty(msg.getLocalPath())) {
//                            data.setmUrl(msg.getContent());
//                            if(FileUtil.isFile(msg.getContent())){
//                                data.setUrlOrPath(UrlOrPathStata.STATE_PATH); 
//                            }else {
//                                data.setUrlOrPath(UrlOrPathStata.STATE_URL);
//                            }
//                        } else {
//                            data.setmUrl(msg.getLocalPath());
//                            data.setUrlOrPath(UrlOrPathStata.STATE_URL);
//                        }
//                    }
//                } else {
//                    data.setmUrl(msg.getContent());
//                    data.setUrlOrPath(UrlOrPathStata.STATE_URL);
//                }
//                data.setmType(LoadImageUrl.STYLE_NAME_IMAGE_SMALL);
//                pictures.add(data);
//            }
//            s.index = index;
//            s.ps = pictures;
//            return s;
        	 
        	
        	return null;
            
            
            
            
        }

        @Override
        protected void onPostExecute(MessageImgStatus s) {
            pictures = s.ps;
            index = s.index;
            setAdapter();
        }
    }

    /**
     * 自定义ViewPagerAdapter
     * @author bo
     *
     */
    class SamplePagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return pictures.size();
        }

        @Override
        public View instantiateItem(ViewGroup container, int position) {
        	
            LayoutParams p = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            FrameLayout layout = new FrameLayout(ViewPagerActivity.this);
            layout.setLayoutParams(p);
            ProgressBar bar = new ProgressBar(ViewPagerActivity.this);
            FrameLayout.LayoutParams barLayoutParam = new FrameLayout.LayoutParams(50, 50);
            barLayoutParam.gravity = Gravity.CENTER;
            bar.setLayoutParams(barLayoutParam);
            PhotoView photoView = new PhotoView(container.getContext());
            barLayoutParam = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            photoView.setLayoutParams(barLayoutParam);
            layout.addView(photoView);
            layout.addView(bar);
            // Now just add PhotoView to ViewPager and return it
            container.addView(layout, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

            setPhotoPath(photoView, bar, position);
            if(flag != Param.FLAG_CHOOSE_PHOTO){
            	setOpertionDivVisible(false);
            }
            //必须这样调用点击事件
            photoView.onClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                	setOpertionDivVisible(!(header.getVisibility()==View.VISIBLE));
                }
            });
            return layout;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            Log.i("yy2", "destroyItem " + position + "," + object);
            ViewGroup root = (ViewGroup) object;
            PhotoView pv = (PhotoView) root.getChildAt(0);
            Drawable d = pv.getDrawable();
            if (d != null && d instanceof BitmapDrawable) {
                Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
                if (bitmap != null && !bitmapSets.contains(bitmap)) {
                    bitmap.recycle();
                }
            }
            container.removeView(root);
            photoViews.remove(pv);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void finishUpdate(ViewGroup container) {
            super.finishUpdate(container);
        }

        @Override
        public void startUpdate(ViewGroup container) {
            super.startUpdate(container);
            setHeardTitleContent(mViewPager.getCurrentItem() + 1 + " / " + pictures.size());
        }

        @Override
        public float getPageWidth(int position) {
            return super.getPageWidth(position);

        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }
    }

    private Set<PhotoView> photoViews = new HashSet<PhotoView>();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁所有ImageView,及所有图片
        for (PhotoView v : photoViews) {
            Drawable d = v.getDrawable();
            if (d != null && d instanceof BitmapDrawable) {
                Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
                if (bitmap != null) {
                    if (!bitmapSets.contains(bitmap)) {
                        bitmap.recycle();
                    }
                }
            }
        }
        photoViews.clear();
        bitmapSets.clear();
    }

    /**
     * 显示本图片
     * 
     * @param photoView  要显示的imageView
     * @param bar   进度条
     * @param index  图片的索引
     */
    public void setPhotoPath(PhotoView photoView, final ProgressBar bar, int index) {
        // /mnt/sdcard/tencent/QQ_Images/f9e8d2bb-bbd7-4891-bdfa-76c0fa0ebbad.jpg
        photoViews.add(photoView);
        setHeardRightContent(flag);
        final String uri = pictures.get(index).getmUrl();
        int isUri = pictures.get(index).getUrlOrPath();
        MyLog.i(TAG, "setPhotoPath:" + uri + ",isUri:" + isUri);
        if (UrlOrPathStata.STATE_PATH == isUri) {
            showPictureByPath(uri, photoView, bar);
        } else {
            // showPictureSmall(uri, pictures.get(index).getmType(), photoView);
            showPictureByUrl(uri, pictures.get(index).getmType(), photoView, bar);
        }
    }

    /**
     * 通过本地路径显示本地图片
     * 
     * @param uri
     * @param photoView
     * @param bar
     */
    private void showPictureByPath(String uri, PhotoView photoView, final ProgressBar bar) {
    	
        LoadImageFile loadImage = new LoadImageFile(uri, false, true, PictureUtil.DISPLAY_SCREEN_WIDTH,
                PictureUtil.DISPLAY_SCREEN_HEIGHT);
        MyImageFetcher.getInstance().loadImage(loadImage, photoView, new ImageWorker.Callback() {
            @Override
            public void onProgressEnd(LoadImage data) {
                Log.i("yy", "onProgressEnd loadImage:" + data.getSourceCacheKey());
                UiUtilities.setVisibilitySafe(bar, View.GONE);
            }

            @Override
            public void onProgress(LoadImage data, long progress) {
                Log.i("yy", "onProgress loadImage:" + data.getSourceCacheKey() + "," + progress);
            }
        });
    }

    /**
     * 通过 uri 显示图片
     * 
     * @param uri
     * @param photoView
     * @param bar
     */
    private void showPictureByUrl(final String uri, final String type, final PhotoView photoView, final ProgressBar bar) {
        new AsyncTask<Void, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(Void... params) {
                try {
                    LoadImageUrl data = new LoadImageUrl(uri, type);
                    return MyImageFetcher.getInstance().getThumbsBitmap(data);
                } catch (Throwable e) {
                    Log.e(TAG, "", e);
                }
                return null;
            }

            protected void onPostExecute(Bitmap result) {
                if (result != null) {
                    bitmapSets.add(result);
                }
                LoadImageUrl loadImage = new LoadImageUrl(uri, null, false, true, PictureUtil.DISPLAY_SCREEN_WIDTH,
                        PictureUtil.DISPLAY_SCREEN_HEIGHT,false);
                MyImageFetcher.getInstance().loadImage(loadImage, photoView, result, new ImageWorker.Callback() {
                    @Override
                    public void onProgressEnd(LoadImage data) {
                        Log.i("yy", "onProgressEnd loadImage:" + data.getSourceCacheKey());
                        UiUtilities.setVisibilitySafe(bar, View.GONE);
                    }

                    @Override
                    public void onProgress(LoadImage data, long progress) {
                        Log.i("yy", "onProgress loadImage:" + data.getSourceCacheKey() + "," + progress);
                    }
                });
            };
        }.executeParallel();
    }
	/**
	 * 设置布局
	 */
    private void setContentView() {
        setContentView(R.layout.show_large_photo);
        mainMereg = (FrameLayout) findViewById(R.id.show_large_megre);
        // 头部
        header = (LinearLayout) findViewById(R.id.show_large_header);
        leftbt = (Button) findViewById(R.id.show_large_btn_left_title);
        rightbt = (Button) findViewById(R.id.show_large_btn_right_title);
        title = (TextView) findViewById(R.id.show_large_center_title);
        checkBox = (ImageView) findViewById(R.id.imageview_check);
        bottom = (LinearLayout) findViewById(R.id.show_large_bottom);
        header.setBackgroundColor(getResources().getColor(R.color.common_blick_text_color));
        setOpertionDivVisible(false);
        rightbt.setOnClickListener(this);
        leftbt.setOnClickListener(this);
        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        mViewPager.setOnClickListener(new OnClickListener() {//点击ViewPager隐藏或显示头布局
            @Override
            public void onClick(View arg0) {
                if (header.getVisibility() == View.GONE) {
                	setOpertionDivVisible(true);
                } else {
                	setOpertionDivVisible(false);
                }
            }
        });
        mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {
				if(pictures!=null&&pictures.size()>position&&
						flag == Param.FLAG_CHOOSE_PHOTO){
					PictureData item = pictures.get(position);
					checkBox.setBackgroundDrawable(item.isSelect() ? 
							getResources().getDrawable(R.drawable.common_checked1_state) :
							getResources().getDrawable(R.drawable.common_uncheck_state));
				}
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				
			}
		});
        
        checkBox.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				int position = mViewPager.getCurrentItem();
				if(pictures!=null&&pictures.size()>position&&
						flag==Param.FLAG_CHOOSE_PHOTO){
					PictureData item = pictures.get(position);
					boolean isSelect = item.isSelect();
					if(!isSelect){
						if(curSelectedCount+1>maxSelectCount){
							Toast.makeText(ViewPagerActivity.this,String.format(getString(R.string.photo_max_choose), maxSelectCount), 
									Toast.LENGTH_SHORT).show();
						}else{
							checkBox.setBackgroundDrawable(getResources().getDrawable(R.drawable.common_checked1_state));
							curSelectedCount ++;
							item.setSelect(true);
						}
					}else{
						checkBox.setBackgroundDrawable(getResources().getDrawable(R.drawable.common_uncheck_state));
						curSelectedCount --;
						item.setSelect(false);
						
					}
					rightbt.setBackgroundResource(android.R.color.transparent);
	    			rightbt.setText(String.format(getString(R.string.sure_choose), curSelectedCount));
					
				}
			}
		});
    }

    /**
     * 给Viewpager设置Adapter
     */
    private void setAdapter() {
        adapter = new SamplePagerAdapter();
        mViewPager.setAdapter(adapter);
        mViewPager.setCurrentItem(index);
        PictureData pictureData = pictures.get(index);
        if(pictureData.isSelect()){
        	checkBox.setBackgroundDrawable(getResources().getDrawable(R.drawable.common_checked1_state));
        }else{
        	checkBox.setBackgroundDrawable(getResources().getDrawable(R.drawable.common_uncheck_state));
        }
        
    }

    /**
     * 设置操作栏隐藏显示
     * @param isVisible
     */
    private void setOpertionDivVisible(boolean isVisible){
    	if(isVisible){
    		header.setVisibility(View.VISIBLE);;
    		bottom.setVisibility(View.VISIBLE);;
    	}
    	else{
    		header.setVisibility(View.GONE);;
    		bottom.setVisibility(View.GONE);;
    	}
    	if(flag != Param.FLAG_CHOOSE_PHOTO){
    		bottom.setVisibility(View.GONE);;
		}
    }

    /**
     * 头部标题内容
     */
    private void setHeardTitleContent(String centerStr) {
        if (null != centerStr) {
            title.setText(centerStr);
        }
    }

    /**
     * 右边头部内容
     */
    private void setHeardRightContent(int flag) {
        switch (flag) {
            case Param.TITLE_RIGHT_SHOW__NONE:
                rightbt.setBackgroundDrawable(null);
                break;
            case Param.FLAG_PUBLISH:
                rightbt.setBackgroundResource(R.drawable.show_larger_img_del);
                break;
            case Param.FLAG_MSGCHAT:
                rightbt.setBackgroundResource(R.drawable.show_larger_img_show_dailog);
                break;
            case Param.FLAG_FRIEND:
                rightbt.setBackgroundResource(R.drawable.show_larger_img_show_dailog);
                break;
            case Param.FLAG_CHOOSE_PHOTO:
            	rightbt.setBackgroundResource(android.R.color.transparent);
    			rightbt.setText(String.format(getString(R.string.sure_choose), curSelectedCount));
            	break;
            default:
                rightbt.setBackgroundResource(R.drawable.show_larger_img_show_dailog);
                break;
        }
    }

    @Override
    public void onClick(View arg0) {
        if (arg0.getId() == R.id.show_large_btn_right_title) {
            switch (flag) {
                case Param.FLAG_PUBLISH:
                    DialogFactory.chooseDialog(this, "要删除这张照片吗？", "确定", new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            int currentIndex = mViewPager.getCurrentItem();
                            PictureData data = pictures.remove(currentIndex);
                            if (null != data) {
                                if (null == leftData) {
                                    leftData = new ArrayList<Integer>();
                                }
                                leftData.add(currentIndex);
                                adapter.notifyDataSetChanged();
                                mViewPager.setCurrentItem(mViewPager.getCurrentItem());
                                setHeardTitleContent(mViewPager.getCurrentItem() + " / " + pictures.size());
                            }
                            if (pictures.size() == 0) {
                            	finishReturn();
                            }
                        }
                    });
                    break;
                case Param.FLAG_CHOOSE_PHOTO:
                	Intent intent = new Intent();
                	intent.putExtra("select_list", pictures);
                	setResult(PhotoActivity.ResultParam.REQUEST_CODE_SELECT_PHOTO, intent);
                    finish();
                	break;
                default:
                    menuWindow = new PupDialog(this, "16", new PupEvent() {
                        @Override
                        public void itemOnClick(PupDialog pupid, View item, int position) {
                            menuWindow.dismiss();
                            switch (position) {
                                case 0:
                                    PictureData data = pictures.get(mViewPager.getCurrentItem());
                                    if (data == null) {
                                        return;
                                    }
                                    String copyFilePath = null;
                                    if (data.getUrlOrPath() == UrlOrPathStata.STATE_PATH) {
                                        copyFilePath = data.getmUrl();
                                    } else {
                                    	String cacheKey = LoadImageUrl.getCacheKey(data.getmUrl(), PictureUtil.DISPLAY_SCREEN_WIDTH, PictureUtil.DISPLAY_SCREEN_HEIGHT, false);
                                        // 根据url 找到本地路径
                                        copyFilePath = MyImageFetcher.getInstance().getLocalPathByUrl(cacheKey);
                                    }
                                    if (TextUtils.isEmpty(copyFilePath)) {
                                        Toast.makeText(getApplicationContext(), R.string.fetch_source_bitmap_url_faied,
                                                Toast.LENGTH_LONG).show();
                                        return;
                                    }
                                    String copyPath = FileUtil.copyImageFile2SdCard(copyFilePath,
                                            FileUtil.COPY_FILE_PATH);
                                    if (null == copyPath || "".equals(copyPath)
                                            || FileUtil.SAVE_FILE_STATUS_SYSTEM_ERROR.equals(copyPath)) {
                                    	MyToast.show(ViewPagerActivity.this,
                                                getString(R.string.show_larger_img_save_fail));
                                    } else if (FileUtil.SAVE_FILE_STATUS_SDCARD_ERROR.equals(copyPath)) {
                                    	MyToast.show(ViewPagerActivity.this,
                                                getString(R.string.show_larger_img_save_sdcard_isnull) );
                                    } else if (FileUtil.SAVE_FILE_STATUS_MEMORY_ERROR.equals(copyPath)) {
                                    	MyToast.show(ViewPagerActivity.this,
                                                getString(R.string.show_larger_img_save_memorry_error));
                                    } else {
                                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                                        try {// nexus 7适配
                                            Uri uri = Uri.parse("file://" + copyPath);
                                            intent.setData(uri);
                                            sendBroadcast(intent);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        } finally {
                                            MyToast.show(ViewPagerActivity.this,
                                                    getString(R.string.show_larger_img_save_finish));
                                        }
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                    });
                    // 显示窗口
                    menuWindow.showAtLocation(mainMereg, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                    break;
            }
        } else if (arg0.getId() == R.id.show_large_btn_left_title) {
        	finishReturn();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
            	finishReturn();
                break;

            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void finishReturn() {
        if (flag == Param.FLAG_PUBLISH) {
            Intent intent = new Intent();
            if (null != leftData) {
                intent.putIntegerArrayListExtra("leftData", leftData);
            }
            setResult(RESULT_OK, intent);
            finish();
        } 
        else if(flag == Param.FLAG_CHOOSE_PHOTO){
        	Intent intent = new Intent();
        	intent.putExtra("select_list", pictures);
        	setResult(RESULT_CANCELED, intent);
            finish();
        }
        else {
            finish();
        }
    }
}
